package csu.web.mypetstore.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import csu.web.mypetstore.mapper.AccountMapper;
import csu.web.mypetstore.mapper.SignonMapper;
import csu.web.mypetstore.pojo.Account;
import csu.web.mypetstore.pojo.Signon;
import csu.web.mypetstore.service.AccountService;
import csu.web.mypetstore.service.ImageService;
import csu.web.mypetstore.utils.JwtHelper;
import csu.web.mypetstore.utils.Result;
import csu.web.mypetstore.utils.ResultToJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account>
        implements AccountService{
    @Autowired
    private SignonMapper signonMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private ImageService imageService;

    @Autowired
    private JwtHelper jwtHelper;




    @Override
    public Account getAccount(String username)
    {
        Wrapper<Signon>wrapper=new LambdaQueryWrapper<Signon>()
                .eq(Signon::getUsername,username);
        Signon signon=signonMapper.selectOne(wrapper);

        Wrapper<Account>wrapper2=new LambdaQueryWrapper<Account>()
                .eq(Account::getUserid,signon.getId());
        Account account=accountMapper.selectOne(wrapper2);
        account.setPassword(signon.getPassword());
        account.setImage(signon.getImage());
        account.setUsername(signon.getUsername());

        return account;

    }

    @Override
    public void insertAccount(Integer userId, String password, String email, String firstName, String lastName, String status, String address1, String address2, String city, String state, Integer zip, String country, String phone) {
        Account account=new Account();

        account.setPassword(password);
        account.setUserid(userId);
        account.setEmail(email);
        account.setFirstname(firstName);
        account.setLastname(lastName);
        account.setStatus(status);
        account.setAddr1(address1);
        account.setAddr2(address2);
        account.setCity(city);
        account.setState(state);
        account.setZip(zip);
        account.setPhone(phone);
        account.setCountry(country);
        accountMapper.insert(account);
    }

    @Override
    public void insertSignon(String username, String password,String image) {
        Signon signon=new Signon();
        signon.setUsername(username);
        signon.setPassword(password);
        signon.setImage(image);

        signonMapper.insert(signon);

    }
    @Override
    public void updateSignon(Integer userId,String username, String password,String image) {
        // 创建查询条件，查找用户名对应的Signon对象
        Wrapper<Signon> wrapper = new LambdaQueryWrapper<Signon>()
                .eq(Signon::getId, userId);

        // 从数据库中获取Signon对象
        Signon signon = signonMapper.selectOne(wrapper);

        // 检查是否找到了对应的Signon对象
        if (signon != null) {

            signon.setPassword(password);
            signon.setUsername(username);
            signon.setImage(image);
            signonMapper.update(signon, wrapper);
        } else {
            // 如果没有找到用户，抛出异常
            throw new RuntimeException("找不到用户名为 " + username + " 的用户");
        }
    }

    @Override
    public void updateAccount(String email, String firstname, String lastname, String addr1, String addr2, String city, String state, String zip, String country, String phone, String username) {

    }


    @Override
    public void deleteAccount(String username) {
        Wrapper<Signon>wrapper2=new LambdaQueryWrapper<Signon>()
                .eq(Signon::getUsername,username);
        Signon signon=signonMapper.selectOne(wrapper2);
        Wrapper<Account>wrapper=new LambdaQueryWrapper<Account>()
                .eq(Account::getUserid,signon.getId());
        accountMapper.delete(wrapper);
        signonMapper.delete(wrapper2);
    }




    @Override
    public void updateAccount(Account account) {
        updateSignon(account.getUserid(),account.getUsername(),account.getPassword(),account.getImage());
        LambdaUpdateWrapper<Account> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Account::getUserid, account.getUserid());
        accountMapper.update(account, updateWrapper);
    }

    @Override
    public int getUserId(String username) {
        Wrapper<Signon>wrapper=new LambdaQueryWrapper<Signon>()
                .eq(Signon::getUsername,username);
        Signon signon=signonMapper.selectOne(wrapper);

            return signon.getId();

    }

    @Override
    public Result login(String username, String password) {
        Wrapper<Signon>wrapper=new LambdaQueryWrapper<Signon>()
                .eq(Signon::getUsername,username);
        Signon signon=signonMapper.selectOne(wrapper);

        if(signon==null)
        {
            return Result.success(10,"用户名不存在");
        }
        else {
            if(!password.equals(signon.getPassword()))
            {
                return Result.success(11,"密码错误");
            }
            else {
                String token=jwtHelper.createToken(username);
                Account account=getAccount(username);
                Map<String,Object> map=new HashMap<>();
                map.put("token",token);
                map.put("account",account);
                return Result.success(map);
            }
        }
    }

    @Override
    public Result register(Account account, MultipartFile file) {
        if(isUsernameExist(account.getUsername()))
        {
            return Result.success("用户名已存在");
        }

        Signon signon=new Signon();
        signon.setUsername(account.getUsername());
        signon.setPassword(account.getPassword());
        signon.setImage(imageService.saveImage(file));
        signonMapper.insert(signon);
        account.setUserid(signon.getId());
        accountMapper.insert(account);
        //注册成功返回token，以及用户信息
        String token=jwtHelper.createToken(account.getUsername());
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("account",account);
        return Result.success(map);
    }

    @Override
    public boolean isUsernameExist(String username) {
        Wrapper<Signon>wrapper=new LambdaQueryWrapper<Signon>()
                .eq(Signon::getUsername,username);
        Signon signon=signonMapper.selectOne(wrapper);
        if(signon!=null)
        {
            return true;
        }
        return false;
    }
}




